<template>
  <div class="home-content">
    <div class="home-left">
      <div class="home-left-content ">
        <el-card class="home-left-top userInfo" >
          <template #header>
            <span>考生信息</span>
          </template>
          <div class="userInfoContent">
            <div class="userimg">
               <img :src="userStore.avaterUrl" class="avatar" v-if="userStore.avaterUrl"/>
               <img :src="userimg" class="avatar default" v-else/>
            </div>
            <div>
              <div class="info">
                <span class="key"><UserOutlined  style="color:#2db7f5"/></span><span class="val">{{ userStore.name }}</span>
                
              </div>
              <div class="info">
                <span class="key"><PhoneOutlined style="color:#87d068"/></span><span class="val">{{ userStore.phone }}</span>
              </div>
              <div class="info">
                <span class="key"><TeamOutlined style="color:#f50"/></span><span class="val">{{ userStore.orgName }}</span>
              </div>
            </div>
          </div>
        </el-card>
        <div class="testData">
          <el-card class="home-left-top zsTest" >
            <template #header>
              <span>正式考试概览</span>
            </template>
            <div class="home-left-top-content exam-section">
              <div class="exam-group">
                <div class="exam-item">
                  <span class="label">正在进行的考试：</span>
                  <span class="value" style="color: #25b864">{{statis.jxZsExam}}</span>
                </div>
                <div class="exam-item">
                  <span class="label" >考试总场数：</span>
                  <span class="value" style="color: #24b0fb">{{statis.allZsExam}}</span>
                </div>
                <div class="exam-item">
                  <span class="label">考试平均分：</span>
                  <span class="value" style="color: #ff9933">{{statis.avgZsExam?statis.avgZsExam:'-'}}</span>
                </div>
              </div>
            </div>
          </el-card>
          <el-card class="home-left-top mockTest" >
            <template #header>
              <span>模拟考试概览</span>
            </template>
            <div class="home-left-top-content exam-section">
              <div class="exam-group">
                <div class="exam-item">
                  <span class="label">正在进行的考试：</span>
                  <span class="value" style="color: #25b864">{{statis.jxMockExam}}</span>
                </div>
                <div class="exam-item">
                  <span class="label">考试总场数：</span>
                  <span class="value" style="color: #24b0fb">{{statis.allMockExam}}</span>
                </div>
                <div class="exam-item">
                  <span class="label">考试平均分：</span>
                  <span class="value" style="color: #ff9933">{{statis.avgMockExam?statis.avgMockExam:'-'}}</span>
                </div>
              </div>
            </div>
          </el-card>
         </div>

     
      </div>
     
      <div class="home-left-bottom">
        <el-card class="home-left-bottom-left" >
          <template #header>
            <span>考试日程</span>
          </template>
          <el-calendar
            ref="calendarRef"
            v-model="calendar"
            class="home-left-bottom-left-calendar"
          >
            <template #header="{ date }">
              <span>{{ date }}</span>
              <el-button-group>
                <el-button size="small" @click="calendarUpdate('prev-month')">
                  上一月
                </el-button>
                <el-button size="small" @click="calendarUpdate('today')"
                  >今天</el-button
                >
                <el-button size="small" @click="calendarUpdate('next-month')">
                  下一月
                </el-button>
              </el-button-group>
            </template>
            <template #date-cell="{ data }">
              <el-popover
                v-if="hasCurMonth(data.date) && getTaskList(data.date).length"
                title=""
                :width="580"
                trigger="hover"
              >
                <template #reference>
                  <span>{{
                    hasCurMonth(data.date) ? dayjs(data.date).get("date") : ""
                  }}</span>
                </template>
                <el-table :data="getTaskList(data.date)">
                  <el-table-column
                   
                    property="name"
                    label="名称"
                    align=""
                  >
                    <template #default="scope">
                      <span
                        v-if="scope.row.type === 1"
                        class="iconfont icon-diannao"
                      ></span>
                      <span
                        v-if="scope.row.type === 2"
                        class="iconfont icon-piyue"
                      ></span>
                      {{ scope.row.name }}
                    </template>
                  </el-table-column>
                  <el-table-column  property="" label="考试时间" align="center">
                    <template #default="scope">{{ scope.row.startTime }}<br />{{ scope.row.endTime
                        }}</template>
                </el-table-column>
                </el-table>
              </el-popover>
              <span v-else>{{
                hasCurMonth(data.date) ? dayjs(data.date).get("date") : ""
              }}</span>
              <div
                v-if="hasCurMonth(data.date) && getTaskList(data.date).length"
                class="home-left-bottom-left-calendar-task"
              ></div>
            </template>
          </el-calendar>
        </el-card>
        <div class="home-left-bottom-right">
          <el-card class="testInfo">
            <template #header>
              <span>正在进行的正式考试</span>
            </template>
            <el-scrollbar max-height="calc((100vh - 380px) / 2)" v-if="todoExamList.length">
              <div
                v-for="todoExam in todoExamList"
                class="home-left-bottom-right-row"
              >
                <div>
                  <el-text tag="b">{{ todoExam.examName }}</el-text
                  ><br />
                  <el-text type="info" size="small"
                    >{{ todoExam.examStartTime.replace(/:\d\d$/, '') }} -
                    {{ todoExam.examEndTime.replace(/:\d\d$/, '') }}</el-text
                  >
                </div>
    
                <el-button type="primary" plain @click="toExam(todoExam)"
                  >开始考试</el-button
                >
              </div>
              
            </el-scrollbar>
            <el-empty class="testInfoempty" :image-size="120" v-if="!todoExamList.length" description="暂无考试" />
          </el-card>
          <el-card class="home-right-bulletin" >
            <template #header>
              <span>公告列表</span>
            </template>
            <div class="bulletinListpage" v-if="bulletinListpage.total !== 0">
              <div
              v-for="bulletin in bulletinListpage.list"
              class="home-right-bulletin-content"
              @click="bulletinShow(bulletin)"
            >
              <span class="home-right-bulletin-content-name">{{
                bulletin.title
              }}</span>
              <span>{{
                dayjs(bulletin.startTime, "YYYY-MM-DD HH:mm:ss").format(
                  "YYYY-MM-DD"
                )
              }}</span>
            </div>
            </div>
            
            <el-empty class="bulletinempty" :image-size="100" v-else description="暂无公告" />
          </el-card>
        </div>
      </div>
    </div>
    <div class="home-right">
      <el-card class="mockContent" style="background-color: #fafafa">
        <template #header>
          <span>模拟考试</span>
        </template>
        <div class="mockItem ">
          <div v-if="mockList?.id && mockList?.state!=1" class="home-left-bottom-right-row">
            <div>
              <el-text tag="b">{{ mockList.paperName }}</el-text
              ><br />
              <el-text type="info" size="small"
                >截止时间：
                <span style="color:#25b864">
                  {{calculateTimeDifference(mockList.answerStartTime,mockList.passTime)}}
                </span></el-text
              >
            </div>
  
            <el-button type="warning"  @click="toMockExam">继续模拟</el-button>
          </div>
          <div v-else class="home-left-bottom-right-row">
            <div>
              <el-text tag="b">模拟考试</el-text>
            </div>
  
            <el-button type="warning"  @click="toMockExam">开始模拟</el-button>
          </div>
        </div>
    
      </el-card>
     
      <el-card class="tkContent">
        <template #header>
          <span>专项练习</span>
        </template>
        <el-scrollbar max-height="440">
          <div
            v-for="todoExer in todoExerList"
            class="home-left-bottom-right-row"
          >
            <div>
              <el-text tag="b">{{ todoExer.name }}</el-text
              >
            </div>
            <el-button type="success" plain @click="toExer(todoExer)"
              >开始练习</el-button
            >
          </div>
          <el-empty v-if="!todoExerList.length" description="暂无练习" />
        </el-scrollbar>
      </el-card>
    </div>
    <a-modal v-model:open="open" :title="modalData.title"
    @cancel="handleCancel"
    :footer="null"
    >
      <p>{{modalData.content}}</p>
    </a-modal>
    <contextHolder />
  </div>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref, watch } from "vue";
import dayjs from "dayjs";
import { useUserStore } from "@/stores/user";
import http from "@/request";
import isBetween from "dayjs/plugin/isBetween";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { notification } from 'ant-design-vue';
import userimg from "@/assets/image/user.png";
import {
  UserOutlined,
  PhoneOutlined,
  TeamOutlined,
} from '@ant-design/icons-vue';
import { Download } from '@element-plus/icons-vue';
//  定义变量
dayjs.extend(isBetween);
const router = useRouter();
const userStore = useUserStore();
const calendarRef = ref(); // 日历引用
const calendar = ref(); // 日历当前日期
const open = ref(false);
const modalData = ref(false)
const statis = reactive({
  // 工作台统计
  allMockExam: 0, // 所有模拟考试
  allZsExam: 0, // 所有正式考试
  avgMockExam: 0, //  模拟考试平均分
  avgZsExam: 0, //  正式考试平均分
  jxMockExam: 0, // 正在模拟考试
  jxZsExam: 0, // 正在正式考试
});
const taskList = ref([] as any[]); // 任务列表（日历悬浮展示）
const todoExamList = ref([] as any[]); // 未完成考试列表
const todoExerList = ref([] as any[]); // 未完成练习列表
const mockList = ref() // 创建一个ref变量，用于存储模拟数据
const [api, contextHolder] = notification.useNotification();
const bulletinListpage = reactive({
  // 公告分页列表
  curPage: 1,
  pageSize: 100,
  total: 0,
  list: [] as any[],
});
const custom = reactive({
  // 自定义内容
  title: "",
  content: "",
});

// 组件挂载完成后，执行如下方法
onMounted(async () => {
  if (!userStore.id) {
    router.push("/login");
  }

  // 更新日历日期
  let {
    data: { data: data },
  } = await http.post("login/sysTime", {});
  let curTime = dayjs(data, "YYYY-MM-DD HH:mm:ss").toDate();
  calendar.value = curTime;

  // 任务查询

  if (userStore.type === 1) {
    // 如果是用户登录
    let {
      data: { data,code },
    } = await http.post("search/homeStat", {}); // 工作台统计
    if(code==200){
      statis.allMockExam = data.allMockExam;
      statis.allZsExam = data.allZsExam;
      statis.avgMockExam = data.avgMockExam;
      statis.avgZsExam = data.avgZsExam;
      statis.jxMockExam = data.jxMockExam;
      statis.jxZsExam = data.jxZsExam;
    }

    let {
      data: { data: data2,code:code2 },
    } = await http.post("myExam/listpage", { pageSize: 100,  }); // 未完成的考试列表
    //只push statue为1或者2
   
    if(code2==200){
      todoExamList.value.push(...data2.list.filter((item: any) => item.state === 1 || item.state === 2));
    }
    let {
      data: { data: data3,code:code3 },
    } = await http.post("myExer/listpage", { pageSize: 100,  }); // 未完成的练习列表
    if(code3==200){
  
      todoExerList.value.push(...data3.list);
    }

    try {
      let {
        data: { data: data4 },
      } = await http.post("myExamMock/hasJxMockExam", {});
        mockList.value = data4;
    } catch (error) {
      console.error("接口调用失败:", error);
      // 处理接口调用失败的情况，比如设置mockList为一个默认值或者进行其他逻辑处理
      mockList.value = {};
    }
    
  }

  // 公告查询
  let {
    data: { code, data: data2 },
  } = await http.post("bulletin/listpage", {
    notice: true,
    curPage: 1,
    pageSize: 10,
  });

  bulletinListpage.list = data2.list.map((bulletin: any) => {
    bulletin.content = bulletin.content.replaceAll("\n", "<br/>");
    return bulletin;
  });
  bulletinListpage.total = data2.total;

  // 自定义信息查询
  let {
    data: { data: data3 },
  } = await http.post("login/custom", {});
  custom.title = data3.title;
  custom.content = data3.content.replaceAll("\n", "<br/>");
});

// 监听属性
watch(
  () => calendar.value,
  async (n, o) => {
    // 日历翻页时，查询指定月的考试列表和练习列表
    if (n && o && dayjs(n).format("YYYY-MM") === dayjs(o).format("YYYY-MM")) {
      // 如果是同一个月份不处理
      return;
    }

    let startTime = dayjs(n).startOf("month").format("YYYY-MM-DD HH:mm:ss");
    let endTime = dayjs(n).endOf("month").format("YYYY-MM-DD HH:mm:ss");
    taskList.value.length = 0;
    if (userStore.type === 1) {
      let {
        data: { data,code },
      } = await http.post("myExam/listpage", {
        pageSize: 100,
        startTime,
        endTime,
      });
      if(code===200){
        taskList.value.push(
        ...data.list.map((task: any) => {
          // 去掉ss
          task.startTime = task.examStartTime;
          task.endTime = task.examEndTime;
          task.name = task.examName;
          task.type = 1;
          return task;
        })
      );
      }
     

    }
  }
);
const handleCancel = ()=>{
  open.value = false
  modalData.value = {}
}
function bulletinShow(bulletin: any) {
  open.value = true
  modalData.value = bulletin
  // api.info({
  //   message: `${bulletin.title}`,
  //   description:
  //   `${bulletin.content}`,
  //   placement:'topRight',
  // });
}
function calculateTimeDifference(dateStr, minutes) {
  // 将日期字符串转换为日期对象
  var dateObj = new Date(dateStr);
  // 设置日期对象分钟数
  dateObj.setMinutes(dateObj.getMinutes() + minutes);

  // 将新的日期时间转换为 YYYY-MM-DD HH:MM 格式返回
  var year = dateObj.getFullYear();
  var month = ("0" + (dateObj.getMonth() + 1)).slice(-2);
  var day = ("0" + dateObj.getDate()).slice(-2);
  var hours = ("0" + dateObj.getHours()).slice(-2);
  var min = ("0" + dateObj.getMinutes()).slice(-2);

  // 返回新的日期时间字符串
  return year + "-" + month + "-" + day + " " + hours + ":" + min;
}

// 日历变更时间
function calendarUpdate(curDate: string) {
  calendarRef.value.selectDate(curDate);
}

// 是否当月日期
function hasCurMonth(curDate: Date) {
  return dayjs(curDate).isBetween(
    dayjs(calendar.value).startOf("month").toDate(), // 当月-01 00:00:00
    dayjs(calendar.value).endOf("month").toDate(), // 当月-31 23:59:59
    null,
    "[]"
  ); // 包含边界
}

// 任务列表获取
function getTaskList(curDate: Date) {
  return taskList.value.filter((task) => {
    return dayjs(curDate).isBetween(
      dayjs(task.startTime, "YYYY-MM-DD HH:mm:ss").startOf("day").toDate(), // 考试开始时间的00:00:00
      dayjs(task.startTime, "YYYY-MM-DD HH:mm:ss").endOf("day").toDate(), // 考试开始时间的23:59:59
      null,
      "[]"
    ); // 包含边界
  });
}

// 公告显示

// 去考试
async function toExam(myExam: any) {
  let examStartTime = dayjs(
    myExam.examStartTime,
    "YYYY-MM-DD HH:mm:ss"
  ).toDate();
  let {
    data: { data },
  } = await http.post("login/sysTime", {});
  let curTime = dayjs(data, "YYYY-MM-DD HH:mm:ss").toDate();
  if (curTime.getTime() < examStartTime.getTime()) {
    ElMessage.error("考试未开始，请等待...");
    return;
  }

  router.push(`/myExam/paper/${myExam.examId}`);
}

async function toMockExam() {
  const examUnStartList = await http.post("myExamMock/publishEx");
  if (examUnStartList.data.code == 200) {
    router.push(`/mockExam/paper/${examUnStartList.data.data}`);
  } else {
    ElMessage.error(examUnStartList.data.msg);
  }
}

// 去练习
async function toExer(myExer: any) {
  let startTime = dayjs(myExer.startTime, "YYYY-MM-DD HH:mm:ss").toDate();
  let {
    data: { data },
  } = await http.post("login/sysTime", {});
  let curTime = dayjs(data, "YYYY-MM-DD HH:mm:ss").toDate();
  if (curTime.getTime() < startTime.getTime()) {
    ElMessage.error("练习未开始，请等待...");
    return;
  }

  router.push(`/myExer/paper/${myExer.id}`);
}
</script>

<style lang="scss" scoped>
.home-content {
  display: flex;
  :deep .el-text {
    color: #333;
  }
  :deep(.el-card) {
    margin-bottom: 12px;
    background: #fafafa;
    position: relative;

    .el-card__header {
      padding: 15px 15px 15px 30px;
      font-size: 14px;
      font-weight: bold;
    }

    .el-card__header::after {
      content: "";
      display: block;
      width: 4px;
      height: 16px;
      background: #409eff;
      position: absolute;
      top: 17px;
      left: 15px;
    }

    .el-card__body {
      font-size: 12px;
      color: var(--el-text-color-regular);
    }
  }

  .home-left {
    width: 980px;
    display: flex;
    flex-direction: column;
    padding-right: 15px;
    .home-left-content{
      display: flex;
      .userInfo{
        width: 420px;
        height: 160px;
        :deep .el-card__body {
          padding: 12px;
        }
        .info{
          font-size: 16px;
          height: 32px;
          color: #333;
          letter-spacing: 1px;
          .key{
            margin-right: 8px;
          }
        }
      }

    }
   

    .home-left-top {
      overflow: initial;

      .home-left-top-content {
        display: flex;

        .home-left-top-content-item {
          flex: 1;
          display: flex;
          justify-content: center;
          cursor: pointer;

          .home-left-top-content-item-num {
            font-size: 28px;
            height: 30px;
            padding-left: 15px;
          }

          .home-left-top-content-item-desc {
            font-weight: bold;
            padding-left: 15px;
            color: var(--el-text-color-secondary);
          }
        }
      }
    }

    .home-left-bottom {
      flex: 1;
      display: flex;
      :deep .el-calendar__header{
        color: #409eff;
        font-size: 16px;
        display: flex;
        align-items: center;
      }
    
      :deep(.home-left-bottom-left) {
        width: 420px;

        .home-left-bottom-left-calendar {
          width: 400px;
          height: 330px;
          font-size: 14px;
          background: #fafafa;

          .el-calendar__header {
            padding: 12px 20px 8px 20px;

            span {
              line-height: 28px;
            }
          }

          td[class*="is-selected"] {
            .el-calendar-day {
              background-color: #409eff;
              border-radius: 5px;
              position: relative;

              span {
                color: white;
              }

              .home-left-bottom-left-calendar-task {
                background-color: var(--el-color-white);
              }
            }
          }

          td {
            border: 0;
            border-radius: 5px;
            position: relative;

            .el-calendar-day {
              height: 35px;
              width: 35px;
              margin: 1px 2px;

              span {
                text-align: center;
                display: inline-block;
                width: 100%;
                height: 100%;
                line-height: 24px;
              }

              .home-left-bottom-left-calendar-task {
                display: block;
                position: absolute;
                bottom: 2px;
                transform: translateX(-50%);
                left: 50%;
                width: 6px;
                height: 6px;
                background-color: var(--el-color-primary);
                border-radius: 50%;
                font-size: 12px;
              }

              &:hover {
                background-color: var(--el-color-primary);
                border-radius: 5px;

                span {
                  color: var(--el-color-white);
                }

                .home-left-bottom-left-calendar-task {
                  background-color: var(--el-color-white);
                }
              }
            }
          }
        }
      }

      :deep(.home-left-bottom-right) {
        flex: 1;
        display: flex;
        flex-direction: column;
        margin-left: 15px;

        .el-card {
          

          .el-card__body {
            padding-top: 0px;


          }
        }
      }
    }
  }

  .home-right {
    flex: 1;
    width: 0;
    display: flex;
    flex-direction: column;

    .home-right-menu {
      .home-right-menu-content {
        display: flex;
        flex-wrap: wrap;
        color: var(--el-text-color-secondary);
        font-weight: bold;

        .home-right-menu-content-item {
          width: 33%;
          display: flex;
          flex-direction: column;
          align-items: center;
          cursor: pointer;

          span {
            display: block;
            padding-top: 10px;
            padding-bottom: 20px;
          }
        }
      }
    }
    :deep .el-card__body {
      padding-top: 0px;

    }
  

    .home-right-custom {
      font-weight: bold;
    }
    .mockContent{
      height: 160px;
      .mockItem{
        border-bottom: none;
        height: 100px;
      }
    }
    .tkContent{
      height: 520px;
    }
  }
  .home-left-bottom-right-row {
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-bottom: 1px solid var(--el-border-color);
    padding: 20px 10px 10px 10px;

    div {
      .el-text {
        font-size: 16px;
      }
    }

    .el-button {
      border: 0;
    }
  }
  .home-right-bulletin {
    height: 238px;
    font-weight: bold;
    :deep .el-card__body {
      padding-top: 20px;
      height: 188px;
    }
    .bulletinempty{
      height: 190px;
    }
    :deep .el-empty__description p{
      color: #333;
      font-weight: 400;
    }
    .bulletinListpage{
      margin-top: 20px;
      font-size: 14px;
      color: #333;
    }
    .home-right-bulletin-content {
      display: flex;
      justify-content: space-between;
      cursor: pointer;
      padding-bottom: 10px;

      .home-right-bulletin-content-name {
        word-break: keep-all;
        white-space: nowrap;
        text-overflow: ellipsis;
        overflow: hidden;
      }
    }
  }
  .testInfo{
    height: 266px;
    flex: 1;
    :deep .el-card__body{
      height: 216px;

    }
    .testInfoempty{
      height: 206px;
      padding: 0;
    }
    :deep .el-empty__description p{
      color: #333;
    }
  }
  .testData{
    flex: 1;
    display: flex;
    margin-left: 15px;
    height: 176px;
    flex-direction: row;
    :deep .el-card__body{
     padding: 0;

    }
    .zsTest{
      flex: 1;
    }
    .mockTest{
      flex: 1;
      margin-left: 14px;
    }
    .exam-section {
      display: flex;
      justify-content: space-between;
    }
    
    .exam-group {
      flex: 1;
      font-size: 16px;
      color: #333;
      margin-left: 14px;
      margin-top: 10px;
    }
    
    .exam-item {
      display: flex;
      align-items: center;
      margin-bottom: 10px;
    }
    
    .exam-item a-icon {
      margin-right: 8px;
    }
    
    .exam-item .label {
      margin-right: 8px;
    }
    
    .exam-item .value {
      font-weight: bold;
    }
  }
}
</style>
<style lang="scss">
.el-message-box-ex {
  max-width: 600px;
}
.userInfoContent{
  display: flex;
  align-items: center;
  .userimg{

  }
  .avatar{
    width: 68px;
    height:90px;
    object-fit: cover; /* 图片填充头像框 */
    margin-right: 8px;
    margin-top: -6px;
  }
  .default{
    margin-top: -24px;
  }
  .avatar-uploader-icon{
    font-size: 50px;
  }
}

</style>